package zhuyun.code.datamanager.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_account.view.*
import zhuyun.code.datamanager.BR
import zhuyun.code.datamanager.R
import zhuyun.code.datamanager.databinding.ItemAccountBinding
import zhuyun.code.datamanager.model.Account

/**
 * @author: Administrator
 * @date: 2021/11/1
 */
class AccountAdapter(val context: Context, private val items: List<Account?>?): RecyclerView.Adapter<AccountAdapter.BindingHolder<ItemAccountBinding>>() {
    private var mCurrentSelectedPosition:Int = -1
    private var mOnLongClickListener:OnLongClickListener? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder<ItemAccountBinding> {
        val binding = DataBindingUtil.inflate<ItemAccountBinding>(LayoutInflater.from(parent.context),
            R.layout.item_account,parent,false)
        return BindingHolder<ItemAccountBinding>(
            binding
        )

    }

    private fun setCurrentSelectedPosition(position: Int){
        if(this.mCurrentSelectedPosition != position){
            val lastSelectedPosition = this.mCurrentSelectedPosition
            this.mCurrentSelectedPosition = position
            notifyItemChanged(lastSelectedPosition)
            notifyItemChanged(this.mCurrentSelectedPosition)
        }


    }

    fun setOnLongClickListener(onLongClickListener:OnLongClickListener){
        this.mOnLongClickListener = onLongClickListener
    }

    override fun getItemCount(): Int {
        if (items != null) {
            return items.size
        }
        return 0
    }

    override fun onBindViewHolder(holder: BindingHolder<ItemAccountBinding>, position: Int) {
        items?.get(position)?.let { holder.bindData(it) }
        if(position == itemCount - 1)
        {
            holder.itemView.divider_line.visibility= View.GONE
        } else {
            holder.itemView.divider_line.visibility = View.VISIBLE
        }
        if(mCurrentSelectedPosition != -1){
            holder.itemView.llRow.isSelected = mCurrentSelectedPosition == position
        }
        holder.itemView.setOnClickListener{
            setCurrentSelectedPosition(position)
        }
        holder.itemView.tag = position
        holder.itemView.setOnLongClickListener {
            setCurrentSelectedPosition(position)
            mOnLongClickListener?.onLongClick(it)
            true
        }
    }

    class BindingHolder<T: ViewDataBinding>(private val viewBinding:T):RecyclerView.ViewHolder(viewBinding.root) {
        fun bindData(item: Account){
            viewBinding.setVariable(BR.account, item)
        }
    }

    interface OnLongClickListener{
        fun onLongClick(v:View)
    }




}